<template>
<el-card class="query-card" shadow="never">
  <div>
    <el-form :ref="id" :id="id" :model="queryParam" :inline="true" :label-width="labelWidth">
      <template v-if="items && items.length > 0" v-for="item in items">
        <!-- node -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='node'" :key="item.label">
          <custom-node-new v-model="queryParam[item.id]" :supportType="item.supportType" />
        </el-form-item>

        <!-- org -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='org'" :key="item.label">
          <org-combox :type="item.type" v-model="queryParam[item.id]" :disabled="item.disabled"></org-combox>
        </el-form-item>

        <!-- input -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater)" :label="_$Z[item.label]" v-if="item.elType==='input'" :key="item.label">
          <el-input :type="item.type" v-model.trim="queryParam[item.id]" :disabled="item.disabled" :clearable="item.clear" />
        </el-form-item>

        <!-- selectTableData input -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')"  :label="_$Z[item.label]" v-if="item.elType==='selectTableData'" :key="item.label">
            <el-input :type="item.type" v-model="queryParam[item.id]" :disabled="true" :clearable="item.clear" ></el-input>
            <custom-btn v-if="!item.disabled" :btn-type="item.btnType" @btn-click="(()=>btnClick(item.method))" label=""></custom-btn>
        </el-form-item>

        <!-- select -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='select'" :key="item.label">
          <custom-combox v-model="queryParam[item.id]" :code-type="item.codeType" :is-all="item.isAll" :disabled="item.disabled" />
        </el-form-item>

        <!-- defSelect -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='defSelect'" :key="item.label">
          <def-combox v-model="queryParam[item.id]" :is-all="item.isAll" :url="item.url" :disabled="item.disabled" />
        </el-form-item>

        <!-- multiSelect -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='multiSelect'" :key="item.label">
          <multiple-combox v-model="queryParam[item.id]" :code-type="item.codeType" :is-all="item.isAll" :disabled="item.disabled" />
        </el-form-item>

        <!-- ndatetime -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='ndatetime'" :key="item.label">
          <el-date-picker v-model="queryParam[item.id]"
                          type="datetimerange"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          :start-placeholder="_$Z['startTime']"
                          :end-placeholder="_$Z['endTime']"
                          :default-time="['00:00:00','00:00:00']"
                          :picker-options="pickerOptions"
                          :disabled="item.disabled"
                          :clearable="item.clear">
          </el-date-picker>
        </el-form-item>

        <!-- datetime -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='datetime'" :key="item.label">
          <el-date-picker v-model="queryParam[item.id]"
                          type="datetime"
                          :placeholder="_$Z['dateTime']"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          :default-time="['00:00:00','00:00:00']"
                          :disabled="item.disabled"
                          :clearable="item.clear">
          </el-date-picker>
        </el-form-item>

        <!-- ndate -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='ndate'" :key="item.label">
          <el-date-picker v-model="queryParam[item.id]"
                          type="daterange"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          :start-placeholder="_$Z['startTime']"
                          :end-placeholder="_$Z['endTime']"
                          :picker-options="pickerOptions"
                          :disabled="item.disabled"
                          :clearable="item.clear">
          </el-date-picker>
        </el-form-item>

        <!-- date -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='date'" :key="item.label">
          <el-date-picker v-model="queryParam[item.id]"
                          type="date"
                          :placeholder="_$Z['dateTime']"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          :disabled="item.disabled"
                          :clearable="item.clear">
          </el-date-picker>
        </el-form-item>
        
        <!-- month -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='month'" :key="item.label">
          <el-date-picker v-model="queryParam[item.id]"
                          type="month"
                          format="yyyy-MM"
                          value-format="yyyy-MM"
                          :disabled="item.disabled"
                          :clearable="item.clear">
          </el-date-picker>
        </el-form-item>

        <!-- year -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='year'" :key="item.label">
          <el-date-picker v-model="queryParam[item.id]"
                          type="year"
                          format="yyyy"
                          value-format="yyyy"
                          :disabled="item.disabled"
                          :clearable="item.clear">
          </el-date-picker>
        </el-form-item>

        <!-- time -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='time'" :key="item.label">
          <el-time-picker v-model="queryParam[item.id]"
                          format="HH:mm:ss"
                          value-format="HH:mm:ss"
                          :start-placeholder="_$Z['startTime']"
                          :end-placeholder="_$Z['endTime']"
                          :disabled="item.disabled"
                          :clearable="item.clear"
                          is-range>
          </el-time-picker>
        </el-form-item>

        <!-- radioDate -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='radioDate'" :key="item.label">
          <radio-datepicker :items="item.radiotypes" :isrange="item.isrange" v-model="queryParam[item.id]" :disabled="item.disabled" :show="item.show" />
        </el-form-item>

        <!-- contrastDate -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='contrastDate'" :key="item.label">
          <time-comparison :items="item.radiotypes" :isrange="item.isrange" v-model="queryParam[item.id]" />
        </el-form-item>

        <!-- switch -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='switch'" :key="item.label">
          <el-switch :type="item.id" v-model="queryParam[item.id]" :disabled="item.disabled" />
        </el-form-item>

        <!-- activeSwitch -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater,'change')" :label="_$Z[item.label]" v-if="item.elType==='activeSwitch'" :key="item.label">
          <el-switch :type="item.id" v-model="queryParam[item.id]" :active-text="item.activeText" :inactive-text="item.inActiveText" @change="(()=>switchChange(queryParam[item.id],item.method?item.method:null))" :disabled="item.disabled" />
        </el-form-item>

        <!-- checkGroup -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater)" :label="_$Z[item.label]" v-if="item.elType==='checkGroup'" :key="item.label">
          <custom-check-group v-model="queryParam[item.id]" :checkboxs="item.checkboxs" @input="((checkList)=>checkGroupChange(checkList,item.method?item.method:null))"></custom-check-group>
        </el-form-item>

        <!-- defCheckGroup -->
        <el-form-item :prop="item.id" :rules="filter_rules(item.validater)" :label="_$Z[item.label]" v-if="item.elType==='defCheckGroup'" :key="item.label">
          <def-check-group v-model="queryParam[item.id]" :url="item.url" :queryparam="item.queryparam" ></def-check-group>
        </el-form-item>
      </template>
    </el-form>
  </div>
</el-card>
</template>

<style lang="scss">
  .query-card {
    .el-card__body {
      padding: 15px 0 0;
    }
  }
</style>

<script>
import CustomCombox from '@/views/platform/components/selector/customCombox'
import customNodeNew from '@/views/platform/components/common/customNodeNew'
import RadioDatepicker from '@/views/platform/components/datePicker/radioDatepicker'
import defCombox from '@/views/platform/components/selector/defCombox'
import multipleCombox from '@/views/platform/components/selector/multipleCombox'
import orgCombox from '@/views/platform/components/common/orgCombox'
import timeComparison from '@/views/platform/components/datePicker/doubleRadioDatepicker'
import customCheckGroup from '@/views/platform/components/checkGroup/customCheckGroup'
import defCheckGroup from '@/views/platform/components/checkGroup/defCheckGroup'

import { parseTime } from '@/utils/index'

export default {
  name: 'customForm',
  data() {
    const i18Keys = ['startTime', 'endTime', 'today', 'yesterday', 'weekAgo', 'monthAgo']
    this.items.forEach(element => {
      i18Keys.push(element.label)
    })
    return {
      queryParam: {},
      i18Keys: i18Keys,
      pickerOptions: {
        shortcuts: [{
          text: this.$t('datePicker.yesterday'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 1)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('datePicker.weekAgo'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('datePicker.monthAgo'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      supportType: ['ndatetime', 'datetime', 'ndate', 'date', 'month', 'year'],
      supportTypeFormat: ['{y}-{m}-{d} {h}:{i}:{s}', '{y}-{m}-{d} {h}:{i}:{s}', '{y}-{m}-{d}', '{y}-{m}-{d}', '{y}-{m}', '{y}'],
      radioType: ['datetime', 'day', 'month', 'year'],
      radioDateFormat: ['{y}-{m}-{d} {h}:{i}:{s}', '{y}-{m}-{d}', '{y}-{m}', '{y}']
    }
  },
  components: { CustomCombox, RadioDatepicker, customNodeNew, defCombox, multipleCombox, timeComparison, orgCombox, customCheckGroup, defCheckGroup },
  props: {
    id: { // 当该组件用到多次时，需设置ID
      type: String,
      default: 'componentQuery'
    },
    defaultValue: { // 设置默认值,格式为：{this.items.id:default}
      type: Object
    },
    items: {
      type: Array,
      required: true
    },
    labelWidth: { // 当该组件用到多次时，需设置ID
      type: String,
      required: false,
      default: '180px'
    }
  },
  methods: {
    // 日期选择
    pick(date) {
      this.items.forEach(value => {
        if (value.elType && ['ndate', 'date', 'ndatetime', 'datetime', 'year', 'month'].indexOf(value.elType) !== -1) {
          this.queryParam[value.id] = date
        }
      })
    },

    // 表单校验
    checkForm(callback) {
      this.$refs[this.id].validate((valid) => {
        if (valid) {
          callback(this.getParam())
        }
      })
    },

    // 移除表单校验
    clearValidate() {
      this.$refs[this.id].clearValidate()
    },

    // 重置表单
    resetFields() {
      this.$refs[this.id].resetFields()
    },

    // 获取非引用类型的查询条件
    getParam() {
      const param = {}
      for (const key in this.queryParam) {
        param[key] = this.queryParam[key]
      }
      return param
    },

    // 按钮点击回调
    btnClick(callback) {
      callback()
    },

    // 开关切换 回调
    switchChange(status, callback) {
      if (callback) {
        callback(status)
      }
    },

    // checkGroup 改变回调
    checkGroupChange(checkList, callback) {
      if (callback) {
        callback(checkList)
      }
    },

    // 设置默认值
    setDefaultValue() {
      const queryParam = {}
      queryParam.id = this.defaultValue.id ? this.defaultValue.id : null
      this.items.forEach(e => {
        queryParam[e.id] = typeof (this.defaultValue[e.id]) !== 'undefined' ? this.defaultValue[e.id] : null
      })
      this.queryParam = queryParam
      // const queryParamTmp = {}
      if (this.defaultValue) {
        this.items.forEach(element => {
          if (!this.defaultValue[element.id]) {
            return true
          }
          if (this.supportType.indexOf(element.elType) >= 0) { // date日期格式化
            const format = this.supportTypeFormat[this.supportType.indexOf(element.elType)]
            if (this.defaultValue[element.id] instanceof Array) {
              const newValue = []
              this.defaultValue[element.id].forEach(element1 => {
                newValue.push(parseTime(element1, format))
              })
              this.queryParam[element.id] = newValue
            } else if (this.defaultValue[element.id] instanceof Date) {
              this.queryParam[element.id] = parseTime(this.defaultValue[element.id], format)
            }
          } else if (element.elType === 'radioDate') {
            // 单选联动日期选择控件日期格式化
            const newValue = {}
            let format = '{y}-{m}-{d}'
            if (this.defaultValue[element.id]) {
              const radio = this.defaultValue[element.id].radio
              const start = this.defaultValue[element.id].start
              const end = this.defaultValue[element.id].end
              if (radio) {
                format = this.radioDateFormat[this.radioType.indexOf(radio)]
                newValue.radio = this.defaultValue[element.id].radio
                if (start instanceof Date) {
                  newValue.start = parseTime(start, format)
                } else {
                  newValue.start = start
                }
                if (end instanceof Date) {
                  newValue.end = parseTime(end, format)
                } else {
                  newValue.end = end
                }
              }
              this.queryParam[element.id] = newValue
            }
          } else if (element.elType === 'multiSelect') {
            this.queryParam[element.id] = this.defaultValue[element.id] ? this.defaultValue[element.id] : []
          } else {
            this.queryParam[element.id] = this.queryParam[element.id] ? this.queryParam[element.id] : null
          }
        })
      }
    }

  },
  created() {
    if (this.defaultValue) {
      this.setDefaultValue()
    }
  },
  watch: {
    // 实时监测组件中对象的默认值，并更新
    defaultValue: {
      handler: function() {
        this.setDefaultValue()
      },
      deep: true
    },
    items(value) {
      value.forEach(element => {
        this.i18Keys.push(element.label)
      })
    }
  }
}
</script>